<template>
  <el-dialog :destroy-on-close="true" :title="formData.id?'编辑部门':'新增部门'" :visible="showDialog" @close="btnCancel">
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form ref="addDept" label-width="120px" :model="formData" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="formData.name"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="formData.code"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="formData.manager"
          style="width: 80%"
          placeholder="请选择"
          @blur="checkManager"
        >
          <el-option
            v-for="user in employeeList"
            :key="user.id"
            :label="user.username"
            :value="user.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="formData.introduce"
          style="width: 80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <el-row slot="footer" type="flex" justify="center">
      <!-- 列被分为24 -->
      <el-col :span="6">
        <el-button type="primary" size="small" @click="btnOK">确定</el-button>
        <el-button size="small" @click="btnCancel">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { addDepartment, getDepartments, getDepartmentDetail, putDepartment } from '@/api/departhment'
import { getEmployeeSimple } from '@/api/employees'
export default {
  props: {
    /* 新增界面 */
    showDialog: {
      type: Boolean,
      default: false
    },
    noData: {
      type: Object,
      required: true
    }
    /* 编辑界面 */

  },
  data() {
    const checkRepeatName = async(rule, val, callback) => {
      // 1. 校验是否重名得出 true / false
      // 拿到所有当前点击的子部门
      // 我们是可以拿到所有部门列表
      // 如果我们再拿到当前点击的部门数据, 就可以筛选出所有子部门
      const { depts } = await getDepartments()
      // console.log('全部部门', depts)
      // console.log('被点击的部门', this.nodeData)
      // console.log('当前点击部门的子部门', depts.filter(item => item.pid === this.nodeData.id))
      // const children = depts.filter(item => item.pid === this.nodeData.id)
      // console.log('是否有重名', children.some(item => item.name === val))
      let isRepeat
      if (this.formData.id) {
        isRepeat = depts
          .filter(item => item.pid === this.noData.pid)
          .some(item => item.name === val && item.id !== this.noData.id)
        console.log(isRepeat)
      } else {
        isRepeat = depts
          .filter(item => item.pid === this.noData.id)
          .some(item => item.name === val)
      }

      // 2. callback 后续处理
      // if (isRepeat) {
      //   callback(new Error('同一父部门下不能重名'))
      // } else {
      //   callback()
      // }
      isRepeat ? callback(new Error('同一父部门下不能重名')) : callback()
    }
    const checkRepeatCode = async(rule, val, callback) => {
      // 1. 拿全部部门数据
      const { depts } = await getDepartments()
      // 2. 如果任何一个的 code 跟 val 则重复了
      let isRepeat
      if (this.formData.id) {
        isRepeat = depts.some(item => item.code === val && item.id !== this.noData.id)
      } else {
        isRepeat = depts.some(item => item.code === val)
      }
      // 3. callback 处理
      isRepeat ? callback(new Error('部门编码必须唯一')) : callback()
    }
    return {
      formData: {
        code: '',
        name: '',
        manager: '',
        introduce: '',
        pid: ''
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          {
            max: 50,
            message: '部门名称要求1-50个字符',
            trigger: 'blur'
          },
          { validator: checkRepeatName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          {
            max: 50,
            message: '部门编码要求1-50个字符',
            trigger: 'blur'
          },
          { validator: checkRepeatCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          {
            trigger: 'blur',
            max: 300,
            message: '部门介绍要求1-50个字符'
          }
        ]
      },
      employeeList: []
    }
  },
  async created() {
    this.employeeList = await getEmployeeSimple()
    console.log(this.employeeList)
  },
  methods: {
    checkManager() {
      setTimeout(() => {
        this.$refs.addDept.validateField('manager')
      }, 100)
    },
    async btnOK() {
      // 校验
      await this.$refs.addDept.validate()
      if (this.formData.id) {
        await putDepartment(this.formData)
      } else {
        // 发请求
        await addDepartment({
          ...this.formData,
          pid: this.noData.id
        })
      }

      // 提示用户
      this.$message.success('操作成功')
      // 页面需要更新
      this.$emit('addDepartment')
      // 关闭弹窗
      // this.showDialog = false
      // this.$emit('closeDialog')
      this.$emit('update:showDialog', false)
    },
    btnCancel() {
      this.formData = {
        code: '',
        name: '',
        manager: '',
        introduce: '',
        pid: ''
      }
      // 1. 清理数据和校验错误
      this.$refs.addDept.resetFields()
      // 2. 关闭弹窗
      this.$emit('update:showDialog', false)
    },
    async getDepartmentDetail(id) {
      this.formData = await getDepartmentDetail(id)
    }
  }

}
</script>

<style>
</style>
